package com.zqj.project.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zqj.project.common.database.mybatis.conditions.Wraps;
import com.zqj.project.common.exception.BizException;
import com.zqj.project.converter.PhoneConverter;
import com.zqj.project.entity.PhonePO;
import com.zqj.project.factory.PhoneFactory;
import com.zqj.project.model.Phone;
import com.zqj.project.repository.PhoneMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Description: PhoneServiceImpl
 * @Author: 22001010704 Zhang Qijian
 * @CreateTime: 2024/11/8 15:39
 * @Version: 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PhoneServiceImpl implements PhoneService {

    private final PhoneMapper phoneMapper;

    @Override
    public IPage<Phone> page(Phone phone, IPage<Phone> page) {
        final Long count = this.phoneMapper.selectCount(PhoneFactory.lbqWrapper(phone));
        if (Objects.equals(0L, count)) {
            return page;
        }
        page.setTotal(count);
        return page.setRecords(PhoneConverter.toPhoneModelList(this.phoneMapper.selectPage(new Page<>(page.getCurrent(), page.getSize(), page.getTotal()), PhoneFactory.lbqWrapper(phone)).getRecords()));
    }

    @Override
    public Phone info(Long id) {
        PhonePO phonePo = this.phoneMapper.selectById(id);
        if (Objects.isNull(phonePo)) {
            throw new BizException("手机不存在");
        }
        return PhoneConverter.toPhoneModel(phonePo);
    }

    @Override
    public Boolean add(Phone phone) {
        if (this.phoneMapper.selectCount(Wraps.<PhonePO>lbQ().eq(StringUtils.isNotBlank(phone.getName()), PhonePO::getName, phone.getName().trim())) > 0L) {
            throw new BizException("手机名称已存在");
        }
        return this.phoneMapper.insert(PhoneConverter.toPhonePo(phone)) == 1;
    }

    @Override
    public Boolean edit(Phone phone) {
        return this.phoneMapper.updateById(PhoneConverter.toPhonePo(phone)) == 1;
    }

    @Override
    public Boolean delete(Long id) {
        return this.phoneMapper.deleteById(id) == 1;
    }

}